package com.yjc.manager.classloader;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义类加载器
 */
public class DynaticClassLoader extends URLClassLoader {
    private Map<String, Class<?>> loadClassMap = new ConcurrentHashMap();

    public DynaticClassLoader(ClassLoader parent, URL[] urls){
        super(urls,parent);
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        Class<?> clazz = loadClassMap.get(className);
        if (clazz == null){
            clazz = super.findClass(className);
            loadClassMap.put(className,clazz);
        }
        return clazz;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return super.loadClass(name);
    }

    /**
     * 卸载类加载器
     */
    public void unload(){
        try {
            for (Map.Entry<String, Class<?>> entry : loadClassMap.entrySet()) {
                String className = entry.getKey();
                loadClassMap.remove(className);
                //如果有destiry方法可以进行资源释放
                try {
                    Class<?> clazz = entry.getValue();
                    Method destory = clazz.getDeclaredMethod("destory");
                    destory.invoke(clazz);
                }catch (Exception e){
                }
            }
            close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
